package org.spiderflow.mailbox.executor.shape;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spiderflow.ExpressionEngine;
import org.spiderflow.context.SpiderContext;
import org.spiderflow.executor.ShapeExecutor;
import org.spiderflow.mailbox.service.MailService;
import org.spiderflow.mailbox.utils.MailboxUtils;
import org.spiderflow.model.Shape;
import org.spiderflow.model.SpiderNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class MailboxlExecutor implements ShapeExecutor {
	/**
	 * 数据源类型
	 */
	public static final String DATASOURCE_ID = "datasourceId";
	/**
	 * 发送地址
	 */
	private static final String MAILBOX_MAIL = "mailboxmail";
	/**
	 * 抄送人地址
	 */
	private static final String MAILBOX_CC = "mailboxcc";
	/**
	 * 暗抄送人地址
	 */
	private static final String MAILBOX_BCC = "mailboxbcc";
	/**
	 * 邮箱抬头
	 */
	private static final String MAILBOX_SUBJECT = "mailboxsubject";
	/**
	 * 邮箱内容
	 */
	private static final String MAILBOX_CONTEXT = "mailboxcontext";
	/**
	 * 附件名称
	 */
	public static final String ENCLOSURE_NAME = "enclosure-name";
	/**
	 * 附件数据
	 */
	public static final String ENCLOSURE_VALUE = "enclosure-value";

	private static Logger logger = LoggerFactory.getLogger(MailboxlExecutor.class);

	@Autowired
	private ExpressionEngine engine;

	@Autowired
	private MailService mailService;

	@Override
	public String supportShape() {
		return "mailboxsendhtml";
	}

	@Override
	public Shape shape() {
		Shape shape = new Shape();
		// web界面上显示的图标
		shape.setImage("");
		// 拖放至容器里时默认的节点名称
		shape.setLabel("电子邮箱发送");
		// 模板文件名
		shape.setName("mailboxsendhtml");
		// 鼠标移动至图标上显示的名称
		shape.setTitle("电子邮箱发送");
		return shape;
	}

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
		int datasourceId = NumberUtils.toInt(node.getStringJsonValue(DATASOURCE_ID),0);
		String mailboxMail = node.getStringJsonValue(MAILBOX_MAIL);
		String mailboxCc = node.getStringJsonValue(MAILBOX_CC);
		String mailboxBcc = node.getStringJsonValue(MAILBOX_BCC);
		String mailboxSubject = node.getStringJsonValue(MAILBOX_SUBJECT);
		String mailboxContext = node.getStringJsonValue(MAILBOX_CONTEXT);
		List<Map<String, String>> enclosure = node.getListJsonValue(ENCLOSURE_NAME, ENCLOSURE_VALUE);
		if(datasourceId == 0){
			logger.error("请选择发信邮箱！");
		}else if (!StringUtils.isNotBlank(mailboxMail)) {
			logger.error("邮箱收件人为空！");
		} else if (!StringUtils.isNotBlank(mailboxSubject)) {
			logger.error("邮箱标题为空！");
		} else if (!StringUtils.isNotBlank(mailboxContext)) {
			logger.error("邮箱发送内容为空！");
		} else {
			JavaMailSenderImpl mailboxTemplate = MailboxUtils.createMailSender(mailService.get(datasourceId + ""));
			MimeMessage message = mailboxTemplate.createMimeMessage();
			MimeMessageHelper mailMessage;
			try {
				mailMessage = new MimeMessageHelper(message, true);
				mailMessage.setFrom(mailboxTemplate.getUsername());
				// 处理收件人变量值
				mailboxMail = engine.execute(mailboxMail, variables).toString();
				mailMessage.setTo(mailboxMail.split(","));
				logger.debug("设置收件人信息成功！");
			} catch (NullPointerException e) {
				logger.error("收件人为空！");
				return;
			} catch (MessagingException e1) {
				logger.error("收件人格式不正确", e1);
				return;
			}
			try {
				// 设置抄送人
				if (StringUtils.isNotBlank(mailboxCc)) {
					mailMessage.setCc(mailboxCc.split(","));
					logger.debug("设置抄送人信息成功！");
				}
			} catch (Exception e) {
				logger.error("抄送人格式不正确", e);
				return;
			}
			try {
				// 设置暗抄送人
				if (StringUtils.isNotBlank(mailboxBcc)) {
					mailMessage.setBcc(mailboxBcc.split(","));
					logger.debug("设置暗抄送人信息成功！");
				}
			} catch (Exception e) {
				logger.error("暗抄送人格式不正确", e);
				return;
			}
			try {
				// 处理标题变量值
				mailboxSubject = engine.execute(mailboxSubject, variables).toString();
				mailMessage.setSubject(mailboxSubject);
				mailMessage.setSentDate(new Date());// 发送时间
				logger.debug("设置发送标题成功！");
			} catch (NullPointerException e) {
				logger.error("标题为空！");
				return;
			} catch (Exception e) {
				logger.error("发送标题数据格式不正确", e);
				return;
			}
			try {
				// 处理发送内容变量值
				mailboxContext = engine.execute(mailboxContext, variables).toString();
				mailMessage.setText(mailboxContext, true);
				logger.debug("设置发送内容成功！");
			} catch (NullPointerException e) {
				logger.error("发送内容为空！");
				return;
			} catch (Exception e) {
				logger.error("发送内容数据格式不正确", e);
				return;
			}
			try {
				if (enclosure != null && enclosure.size() > 0) {
					for (Map<String, String> item : enclosure) {
						String enclosureName = item.get(ENCLOSURE_NAME);
						String enclosureValue = item.get(ENCLOSURE_VALUE);
						byte[] file = (byte[]) engine.execute(enclosureValue, variables);
						InputStreamSource inputStreamSource = new ByteArrayResource(file);
						mailMessage.addAttachment(MimeUtility.encodeWord(enclosureName), inputStreamSource);
					}
				}
			} catch (Exception e) {
				logger.error("附件格式错误:{}", e);
				return;
			}
			try {
				logger.debug("邮箱发送中.......请稍等！");
				mailboxTemplate.send(message);
				logger.debug("邮箱发送成功！");
			} catch (Exception e) {
				logger.error("邮箱发送失败:{}", e);
			}
		}
	}
}
